#include "../libxluploader.h"
#include "sites.h"
#include <assert.h>
#include <iostream>

std::string CSiteTinyPic::parseImageUrl (const std::string &response) {
	if (!m_pcreCodePic || !m_pcreCodeIval || !m_pcreCodeType) {
		return "";
	}

	std::string url = "http://i";

	const int size = 30;
	int ov[size] = {0};
	const char *text = response.c_str();
	int res = pcre_exec(m_pcreCodeIval, NULL, text, response.length(), 0, 0, ov, size);
	if (res != 2) {
		return "";
	}
	url += response.substr(ov[2], ov[3] - ov[2]);
	url += ".tinypic.com/";

	memset (ov, 0, sizeof(ov));
	res = pcre_exec(m_pcreCodePic, NULL, text, response.length(), 0, 0, ov, size);
	if (res != 2) {
		return "";
	}
	url += response.substr(ov[2], ov[3] - ov[2]);

	memset (ov, 0, sizeof(ov));
	res = pcre_exec(m_pcreCodeType, NULL, text, response.length(), 0, 0, ov, size);
	if (res != 2) {
		url += ".jpg";
	} else {
		url += response.substr(ov[2], ov[3] - ov[2]);
	}

	return url;
}

std::string CSiteTinyPic::getUrl() const {
	return "http://www.tinypic.com/";
}


CSiteTinyPic::CSiteTinyPic () {
	m_errPic = m_errIval = m_errType = NULL;

	const char *pattern_pic = "name=\"pic\".value=\"([^\"]*)\"";
	const char *pattern_ival = "name=\"ival\".value=\"([^\"]*)\"";
	const char *pattern_type = "name=\"type\".value=\"([^\"]*)\"";
	int flags = PCRE_BSR_ANYCRLF | PCRE_UTF8 | PCRE_MULTILINE | PCRE_DOTALL;
	m_pcreCodePic = pcre_compile(pattern_pic, flags, &m_errPic, &m_errPicOffset, NULL);
	m_pcreCodeIval = pcre_compile(pattern_ival, flags, &m_errIval, &m_errIvalOffset, NULL);
	m_pcreCodeType = pcre_compile(pattern_type, flags, &m_errType, &m_errTypeOffset, NULL);
}

CSiteTinyPic::~CSiteTinyPic() {
	if (m_pcreCodePic) {
		pcre_free(m_pcreCodePic);
	}
	if (m_pcreCodeIval) {
		pcre_free(m_pcreCodeIval);
	}
	if (m_pcreCodeType) {
		pcre_free(m_pcreCodeType);
	}
}

TCHAR* CSiteTinyPic::getSiteName () {
	return _T("TinyPic.com");
}


#ifdef DEBUG_SIZE_TINYPIC
ISite* debugGetSite() {
	static CSiteTinyPic tp;
	return &tp;
}
#endif
